package com.lujianfei.virusbroadcast.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.lujianfei.lib.sdautolayout.impl.SDAutoLayout;
import com.lujianfei.virusbroadcast.base.BaseMenuWindow;
import com.lujianfei.virusbroadcast.beans.Hospital;
import com.lujianfei.virusbroadcast.beans.Person;
import com.lujianfei.virusbroadcast.cache.SPRepository;
import com.lujianfei.virusbroadcast.factory.PersonPool;
import com.lujianfei.virusbroadcast.widget.MyPanel;

public class MainFrame extends BaseMenuWindow{

	MyPanel panel;
    Thread panelThread;
    
	public MainFrame() {
		super();
		setTitle("新型冠状病毒——感染过程仿真");
		setResizable(false);
		panel = new MyPanel();
		add(panel);
		Hospital.getInstance().setX(getWidth() - Hospital.getInstance().getWidth() -  270);
		Hospital.getInstance().setY(50);
		SDAutoLayout.forComponent(panel).widthIs(getWidth()).heightIs(getHeight());
	}

	@Override
	protected List<MenuBean> getMenuBean() {
		List<MenuBean> menuBeans = new ArrayList<>();
		List<MenuBean> menuOperation = new ArrayList<>();
		List<MenuBean> menuRun = new ArrayList<>();
		menuBeans.add(new MenuBean.Builder().setName("操作").setChilds(menuOperation).create());
		menuOperation.add(new MenuBean.Builder().setName("设置").setActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				SettingDialog settingDialog = new SettingDialog(MainFrame.this,true);
				settingDialog.setOnConfirmListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						stop();
						reset();
					}
				});
				settingDialog.setVisible(true);
			}
		}).create());
		menuOperation.add(new MenuBean.Builder().setName("退出").setActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				exit();
			}
		}).create());
		menuBeans.add(new MenuBean.Builder().setName("运行").setChilds(menuRun).create());
		menuRun.add(new MenuBean.Builder().setName("开始").setActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if (null == panelThread) {
					panelThread = new Thread(panel);
				}
				if( panel.isRunning()) {
					return;
				}
				panelThread.start();				
			}
		}).create());
		menuRun.add(new MenuBean.Builder().setName("停止").setActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				stop();
			}
		}).create());
		menuRun.add(new MenuBean.Builder().setName("重置").setActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				reset();
			}
		}).create());
		return menuBeans;
	}
	

	private void stop() {
		panel.cancel();	
		panel.repaint();
		panelThread = null;
	}
	
	private void reset() {
		panel.reset();
	}
	
	@Override
	protected void onDestroy() {
		stop();
		super.onDestroy();
	}
}
